library flutter_verification_box;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'verification_box_item.dart';

class VerificationBoxController extends ChangeNotifier {
  String _text = '';

  /// 获取当前文本内容
  String get text => _text;

  /// 设置文本内容
  set text(String value) {
    if (_text != value) {
      _text = value;
      notifyListeners();
    }

  }

  /// 设置文本内容（方法形式）
  void setText(String text) {
    this.text = text;
  }

  /// 清空输入内容
  void clear() {
    text = '';
  }

  /// 重置输入框（保持向后兼容）
  void reset() {
    clear();
  }
}

///
/// 验证码输入框
///
class VerificationBox extends StatefulWidget {
  const VerificationBox({
    this.count = 6,
    this.itemWidget = 45,
    this.onSubmitted,
    this.onValueChanged,
    this.type = VerificationBoxItemType.box,
    // this.decoration,
    this.borderWidth = 2.0,
    this.borderRadius = 5.0,
    this.backgroundColor,
    this.textStyle,
    this.focusBorderColor,
    this.borderColor,
    this.unfocus = true,
    this.autoFocus = true,
    this.showCursor = false,
    this.cursorWidth = 2,
    this.cursorColor,
    this.hintTextStyle,
    this.cursorIndent = 10,
    this.cursorEndIndent = 10,
    this.obscureText = true,
    this.verificationBoxController,
  });

  ///
  /// 几位验证码，一般6位，还有4位的
  ///
  final int count;

  ///
  /// 没一个item的宽
  ///
  final double itemWidget;

  ///
  /// 输入完成回调
  ///
  final ValueChanged<String>? onSubmitted;
  final ValueChanged<String>? onValueChanged;

  ///
  /// 每个item的装饰类型，[VerificationBoxItemType]
  ///
  final VerificationBoxItemType type;

  ///
  /// 每个item的样式
  ///
  // final Decoration? decoration;

  ///
  /// 边框宽度
  ///
  final double borderWidth;

  ///
  /// 边框颜色
  ///
  final Color? borderColor;

  ///
  /// 获取焦点边框的颜色
  ///
  final Color? focusBorderColor;

  ///
  /// 背景颜色
  ///
  final Color? backgroundColor;

  ///
  /// [VerificationBoxItemType.box] 边框圆角
  ///
  final double borderRadius;

  ///
  /// 文本样式
  ///
  final TextStyle? textStyle;

  ///
  /// 文本样式
  ///
  final TextStyle? hintTextStyle;

  ///
  /// 输入完成后是否失去焦点，默认true，失去焦点后，软键盘消失
  ///
  final bool unfocus;

  ///
  /// 是否自动获取焦点
  ///
  final bool autoFocus;

  ///
  /// 是否显示光标
  ///
  final bool showCursor;

  ///
  /// 光标颜色
  ///
  final Color? cursorColor;

  ///
  /// 光标宽度
  ///
  final double cursorWidth;

  ///
  /// 光标距离顶部距离
  ///
  final double cursorIndent;

  ///
  /// 光标距离底部距离
  ///
  final double cursorEndIndent;

  final VerificationBoxController? verificationBoxController;

  final bool obscureText;

  //密文字符
  // final String? pwdText;

  @override
  State<StatefulWidget> createState() => _VerificationBox();
}

class _VerificationBox extends State<VerificationBox> {
  late TextEditingController _controller;

  late FocusNode _focusNode;

  var _contentList = [];
  late VoidCallback _resetListener;
  bool _hasFocus = false;

  @override
  void initState() {
    List.generate(widget.count, (index) {
      _contentList.add('');
    });
    _controller = TextEditingController();
    _focusNode = FocusNode();
    _resetListener = () {
      setState(() {
        String newText = widget.verificationBoxController?.text ?? "";
        // 限制文本长度不超过验证码位数
        if (newText.length > widget.count) {
          newText = newText.substring(0, widget.count);
        }
        _controller.text = newText;
        // 更新内容列表
        _contentList = List.filled(widget.count, "");
        for (int i = 0; i < newText.length && i < widget.count; i++) {
          _contentList[i] = newText.substring(i, i + 1);
        }
      });
      // 如果设置了文本内容，不自动获取焦点
      // if ((widget.verificationBoxController?.text ?? "").isEmpty) {
      //   _focusNode.requestFocus();
      // }
    };
    widget.verificationBoxController?.addListener(_resetListener);
    super.initState();
    _focusNode.addListener(_onFocusChange);
  }

  void _onFocusChange() {
    setState(() {
      _hasFocus = _focusNode.hasFocus;
    });
  }

  @override
  void dispose() {
    _focusNode.removeListener(_onFocusChange);

    _focusNode.dispose();
    widget.verificationBoxController?.removeListener(_resetListener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(_focusNode);
      },
      child: Stack(
        children: <Widget>[
          Positioned.fill(
              child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: List.generate(widget.count, (index) {
              return SizedBox(
                width: widget.itemWidget,
                height: widget.itemWidget,
                child: VerificationBoxItem(
                  data: _contentList[index],
                  textStyle: widget.textStyle,
                  hintTextStyle: widget.hintTextStyle,
                  obscureText: widget.obscureText,
                  type: widget.type,
                  backgroundColor: widget.backgroundColor,
                  // decoration: widget.decoration,
                  borderRadius: widget.borderRadius,
                  borderWidth: widget.borderWidth,
                  showBorder: index >= _controller.text.length,
                  borderColor: (_hasFocus && _controller.text.length == index
                          ? widget.focusBorderColor
                          : widget.borderColor) ??
                      widget.borderColor,
                  showCursor: _hasFocus &&
                      widget.showCursor &&
                      _controller.text.length == index,
                  cursorColor: widget.cursorColor,
                  cursorWidth: widget.cursorWidth,
                  cursorIndent: widget.cursorIndent,
                  cursorEndIndent: widget.cursorEndIndent,
                  // isPassword: widget.isPassword,
                  // pwdText: widget.pwdText,
                ),
              );
            }),
          )),
          _buildTextField(),
        ],
      ),
    );
  }

  ///
  /// 构建TextField
  ///
  _buildTextField() {
    return TextField(
      contextMenuBuilder: (context, state) {
        return const SizedBox();
      },
      controller: _controller,
      focusNode: _focusNode,
      decoration: const InputDecoration(
        border: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.transparent)),
        enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.transparent)),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.transparent)),
      ),
      cursorWidth: 0,
      autofocus: widget.autoFocus,
      inputFormatters: [
        FilteringTextInputFormatter.digitsOnly
        // WhitelistingTextInputFormatter(RegExp("[0-9]")),
      ],
      maxLength: widget.count,
      buildCounter: (
        BuildContext context, {
        required int currentLength,
        required bool isFocused,
        required int? maxLength,
      }) {
        return const Text('');
      },
      // obscureText: true,
      keyboardType: TextInputType.number,
      style: const TextStyle(color: Colors.transparent),
      onChanged: _onValueChange,
      enableInteractiveSelection: false,
    );
  }

  _onValueChange(value) {
    for (int i = 0; i < widget.count; i++) {
      if (i < value.length) {
        _contentList[i] = value.substring(i, i + 1);
      } else {
        _contentList[i] = '';
      }
    }
    setState(() {});

    // 同步更新控制器的文本状态（避免循环通知）
    if (widget.verificationBoxController != null &&
        widget.verificationBoxController!._text != value) {
      widget.verificationBoxController!._text = value;
    }

    widget.onValueChanged?.call(value);
    if (value.length == widget.count) {
      if (widget.unfocus) {
        _focusNode.unfocus();
      }
      widget.onSubmitted?.call(value);
    }
  }

  @override
  void didUpdateWidget(VerificationBox oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.verificationBoxController !=
        oldWidget.verificationBoxController) {
      oldWidget.verificationBoxController?.removeListener(_resetListener);
      widget.verificationBoxController?.addListener(_resetListener);
    }
  }
}
